'use strict';

var _ = require('lodash'),
  async = require("async"),
  multiparty = require('multiparty'),
  moment = require('moment');

var fs = require('fs'),
  path = require('path');

(function() {

  var SampleController = {};

  function now() {
    return moment().format('hh:mm:ss');
  }

  SampleController.index = function(req, res) {

    console.log('request:', req.query)

    return res.render('index', {
      'title': 'express restful+ejs demo'
    });
  }

  SampleController.report = function(req, res) {

    var result_str = JSON.stringify(req.body, null, 2);
    console.log(now(), 'received report: ' + result_str);

    return res.jsonResponse(200, 'ok');
  }

  SampleController.upload = function(req, res) {

    async.waterfall([

        function validate(next) {
          console.log(now(), 'start uploading');
          return next();
        },

        function parse(next) {

          var form = new multiparty.Form({
            uploadDir: './tmp/'
          });

          form.parse(req, function(err, fields, result) {

            if (err) {
              console.log(now(), 'parse error: ' + err);
              return next(err);
            } else {
              return next(null, result);
            }

          });
        },

        function save(result, next) {

          var result_str = JSON.stringify(result, null, 2);
          console.log(now(), 'save files: ' + result_str);

          var files = result['upload'];
          var inputFile = files[0];

          var uploadedPath = inputFile.path;
          var dstPath = path.resolve('upload', inputFile.originalFilename);

          //重命名为真实文件名
          fs.rename(uploadedPath, dstPath, function(err) {
            if (err) {
              console.log(now(), 'error to save: ' + err);
              return next(err);
            } else {
              console.log(now(), 'completed to save:' + inputFile.size);
              return next();
            }
          });
        }

      ],
      function(err, result) {
        if (err) {
          return res.jsonResponse(400, err);
        }

        return res.jsonResponse(200, 'ok');
      })
  }

  module.exports = SampleController;
})()
